/**
 * 
 */
package com.wolfpire.system.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

/**
 * 字符串模板解析
 * @author lihd
 *
 */
public class StringTemplateUtil {
	
	private static Logger logger = Logger.getLogger(StringTemplateUtil.class);
	
	/**
	 * ${ }
	 */
	public static final String PATTEN_BRACE = "\\$\\{[^{}]*\\}";
	
	public static String parseTemplate(String origin, String regex, int beginIndex, int endIndex, Map<String, Object> params) {
		logger.info("==============待解析字符串：" + origin);
		Pattern patten = Pattern.compile(regex);
		Matcher matcher = patten.matcher(origin);
		while (matcher.find()) {
			String originKey = matcher.group(0);
			logger.info("==============找到表达式：" + originKey);
			String key = originKey.substring(beginIndex, originKey.length()-endIndex);
			logger.info("==============表达式内部：" + key);
			String value = String.valueOf(params.get(key));
			logger.info("==============map对应的value：" + value);
			origin = origin.replace(originKey, value);
			logger.info("==============替换后的字符串：" + origin);
		}
		return origin;
	}
	
	public static void main(String[] args) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", 10001);
		map.put("name", "lee");
		String str = "你好${id},${name}:";
		str = parseTemplate(str, PATTEN_BRACE, 2, 1, map);
	}
}
